import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { User } from './entity/user.entity';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly jwtService: JwtService,
  ) {}

  async loginAndRegister(params): Promise<any> {
    const username = params.username,
      password = params.password,
      city = params.city;
    const data = await this.userRepository.findOne({ username });
    if (!data) {
      // 生成用户ID
      let userId = parseInt(
        Math.random()
          .toString()
          .split('.')[1]
          .substr(0, 6),
      );
      userId > 99999 ? '' : userId * 10;
      const newUser = await this.userRepository.save({
        userId: userId.toString(),
        username,
        password,
        city,
      });
      return {
        msg: '登录成功',
        data: {
          user: newUser,
          token: this.jwtService.sign({ userId, password }),
        },
      };
    }
    // 用户名存在
    let userId = data.userId,
      psd = data.password;
    if (Object.is(psd, password)) {
      return {
        msg: '登录成功',
        data: {
          user: data,
          token: this.jwtService.sign({ userId, password }),
        },
      };
    }
    return {
      msg: '用户名或密码错误',
      code: 1,
    };
  }

  async forgetPassword(username: string, newPsd: string) {
    const user = await this.userRepository.findOne({ username });
    if (!user) {
      return {
        msg: '用户名不存在',
        code: 1,
      };
    }
    await this.userRepository.update(user, { password: newPsd });
    return {
      msg: '更改成功，请保存好新的密码',
    };
  }

  adminLogin(userId: string, password: string) {
    return {
      msg: '运营后台登录成功',
      data: {
        user: {
          username: 'admin',
          password: 'admin',
        },
        token: this.jwtService.sign({ userId, password }),
      },
    };
  }

  async getUserListByPageIndex(pageIndex: number) {
    let userCount = 0,
      pageData = null,
      queryByPageIndex = `select * from user order by birthTime desc limit ${pageIndex *
        10},10 `,
      queryCount = 'select count(1) from user';

    pageData = await this.userRepository.query(queryByPageIndex);
    userCount = await this.userRepository.query(queryCount);

    return {
      msg: '查询成功',
      data: {
        pageData,
        total: userCount[0]['count(1)'],
      },
    };
  }

  async getUserRiseInfo() {
    let userCount = 0,
      userMonthCount = 0,
      userWeekCount = 0,
      userDayCount = 0,
      queryAllCount = 'select count(1) from user',
      queryMonthCount = `select count(1) from user where date_format(birthTime, '%Y%m') = date_format(now() , '%Y%m')`,
      queryWeekCount = `select count(1) from user where date_sub(now(), interval 7 day) <= date(birthTime)`,
      queryDayCount = `select count(1) from user where to_days(birthTime) = to_days(now())`;

    userCount = await this.userRepository.query(queryAllCount);
    userMonthCount = await this.userRepository.query(queryMonthCount);
    userWeekCount = await this.userRepository.query(queryWeekCount);
    userDayCount = await this.userRepository.query(queryDayCount);
    return {
      msg: '查询成功',
      data: {
        userCount: userCount[0]['count(1)'],
        userMonthCount: userMonthCount[0]['count(1)'],
        userWeekCount: userWeekCount[0]['count(1)'],
        userDayCount: userDayCount[0]['count(1)'],
      },
    };
  }

  async getWeekUserRiseInfo() {
    let one = 0,
      two = 0,
      three = 0,
      four = 0,
      five = 0,
      six = 0,
      seven = 0,
      queryOneCount =
        'select count(1) from user where date_sub(now(), interval 7 day) <= date(birthTime)',
      queryTwoCount =
        'select count(1) from user where date_sub(now(), interval 30 day) <= date(birthTime)',
      queryThreeCount = `select count(1) from user where PERIOD_DIFF(date_format(now(), '%Y%m'), date_format(birthTime, '%Y%m')) =1`,
      queryFourCount = `select count(1) from user where QUARTER(birthTime)=QUARTER(now())`,
      queryFiveCount = `select count(1) from user where QUARTER(birthTime)=QUARTER(DATE_SUB(now(),interval 1 QUARTER))`,
      querySixCount = `select count(1) from user where YEAR(birthTime)=YEAR(NOW())`,
      querySevenCount = `select count(1) from user where year(birthTime)=year(date_sub(now(),interval 1 year))`;

    // 随便定义的查询语句、不准确
    // 近七天
    one = await this.userRepository.query(queryOneCount);
    // 近30天
    two = await this.userRepository.query(queryTwoCount);
    // 上个月
    three = await this.userRepository.query(queryThreeCount);
    // 查询本季度数据
    four = await this.userRepository.query(querySixCount);
    // 查询上季度数据
    five = await this.userRepository.query(querySevenCount);
    //查询本年数据
    six = await this.userRepository.query(queryFourCount);
    //查询上年数据
    seven = await this.userRepository.query(queryFiveCount);

    return {
      msg: '查询成功',
      data: {
        one: one[0]['count(1)'],
        two: two[0]['count(1)'],
        three: three[0]['count(1)'],
        four: four[0]['count(1)'],
        five: five[0]['count(1)'],
        six: six[0]['count(1)'],
        seven: seven[0]['count(1)'],
      },
    };
  }
}
